<?php
/**
 * 邮件推送汇总日志接口
 * 
 * @author kangpengfei
 *
 * ##返回值说明##
 * 0	Success	成功
 * 10001	Empty data	空数据请求
 * 10002	Invalid apikey	无效的apikey
 * 10003	Empty  data detail	空的明细数据
 * 10004	Step error	推送环节错误
 * 10005	Site name error	站点名称错误
 * 10006	Mail type error	邮件类型错误
 * 10007	Failed	操作失败
 *
 *
 * key规则: 采用md5加密 api-push-group-log/index#step#site_name   如:  md5(api-push-group-log/index#2#sammydress)
 */
 
namespace app\controllers\marketing;

use Yii;
use yii\web\Controller;
use app\models\marketing\PushGroupLog;
use app\models\marketing\PushGroupLogRequests;

class ApiPushGroupLogController extends Controller
{
	const STEP_BIGDATA = 1;  //推送环节-大数据
	const STEP_WEBSITE = 2;  //推送环节-网站
	const STEP_EDM = 3;  //推送环节-edm
	const MAIL_TYPE_CART = 1;  //邮件类型-购物车
	const MAIL_TYPE_VIEW = 2;  //邮件类型-浏览记录
	const DEFAULT_API_KEY = "G7d9Ed8JbvS9dfeo123ndOs22isdnrEcX";  //默认接口密钥(测试环境使用)
	
	//推送环节可选项
	protected $stepArr = [
		self::STEP_BIGDATA,
		self::STEP_WEBSITE,
		self::STEP_EDM,
	];
	
	//邮件类型可选项
	protected $mailTypeArr = [
		self::MAIL_TYPE_CART,
		self::MAIL_TYPE_VIEW,
	];
	
	//站点可选项
	protected $siteArr = [
		"sammydress",
		"gearbest",
		"rosewholesale",
		"rosegal",
		"zaful",
		"dresslily",
	];
	
	//返回值可选项
	protected $result = [
		0 => ["code" => "0", "msg" => "Success"],
		1 => ["code" => "10001", "msg" => "Empty data"],
		2 => ["code" => "10002", "msg" => "Invalid apikey"],
		3 => ["code" => "10003", "msg" => "Empty  data detail"],
		4 => ["code" => "10004", "msg" => "Step error"],
		5 => ["code" => "10005", "msg" => "Site name error"],
		6 => ["code" => "10006", "msg" => "Mail type error"],
		7 => ["code" => "10007", "msg" => "Failed"],
	];
	
	//正式环境密钥列表(按推送环节,站点区分)
	protected $apiKeyList = [
		"1" => [
			"default" => "47b1082b8c27c8f9f802bf5ed410ce36"
		],
		"2" => [
			"default" => "fd42f38fbc5123ccd730379de1b2755e",
			"sammydress" => "c073cbe4b577d9d170b9714d2638c5a8",
			"gearbest" => "b4d11c474d7ea80afa7bd25243683c08",
			"rosegal" => "1ea20c1fd7157f32a09a48d0fd961d73",
			"rosewholesale" => "120e4caa12427f26a736ac0dc3407fab",
			"zaful" => "d3930d325180a5ca34f662902c63e808",
			"dresslily" => "bb16d844102a265b82f08b8adecb1b56",
		],
		"3" => [
			"default" => "15c7a923e878bbce40c619e898ba1b34",
		]
	];
	
	//post 数据 : 原始post的数据
	protected $post = [];
	
	//data数据 :  doVaildationData()函数里会对其进行赋值
	protected $data = [];
	
	//站点名称 对应 站点id
	protected $webIndex = [];
	
	public function init()
	{
		parent::init();
		$this->enableCsrfValidation = false;        // 禁用post的csrf验证
		
		//取出配置文件中的站点id对应站点数据
		$webIndex = Yii::$app->params["sites"]["marketing_email"]["web_index"];
		$webIndex = array_flip($webIndex);
		$this->webIndex = $webIndex;
	}
	
	/**
	 * 入口
	 */
	public function actionIndex()
	{
		//默认返回值
		$return = [
			"code" => $this->result[0]["code"],
			"msg" => $this->result[0]["msg"],
		];
		
		try
		{
			//post数据
			$post = Yii::$app->request->post();
			$this->post = $post;
			
			//数据验证
			$this->doVaildationData();
			
			//保存数据
			$pushGroupLogModel = new PushGroupLog();
			$siteId = $this->webIndex[$this->data["site_name"]];  //站点ID
			$siteType = $this->getSiteType($siteId);  //站点类型 0未定义, 1电子, 2服装
			$this->data["site_id"] = $siteId;
			$this->data["site_type"] = $siteType;
			
			//取计划发送日期
			$planParam = [
				"site_id" => $siteId,
				"mail_type" => $this->data["mail_type"],
				"mail_type_arr" => $this->mailTypeArr,
			];
			$planData = $pushGroupLogModel->getPlanSendDate($planParam);
			$this->data["plan_send_date"] = isset($planData["data"]) ? $planData["data"] : "";
			
			//入库
			$result = $pushGroupLogModel->doSavePushGroupLog($this->data);
			if ($result["status"] == "error")
			{
				$return = [
					"code" => $this->result[7]["code"],
					"msg" => $this->result[7]["msg"],
				];
			}
			
			//保存日志(只有合法的数据的才会写入日志)
			$this->doWriteLog($return);
		}
		catch (\Exception $e)
		{
			$return = [
				"code" => $this->result[7]["code"],
				"msg" => $e->getMessage(),
			];
		}
		
		//响应
		die(json_encode($return));
	}
	
        /*
         * 定时把SOA邮件推送汇总日志写入到真实表中
         */
        
        public function actionSynPushGroupLogs()
        {
            ignore_user_abort(true); 
            set_time_limit(0);
        
            $method = yii::$app->request->getMethod();
            $limit = yii::$app->request->$method('limit') ? yii::$app->request->$method('limit') : 5000;
            
            $pushGroupLogModel = new PushGroupLog();
            
            while(1) {
                
                $getSql = "select * from gb_push_group_log where is_sync=0 limit $limit";
                $groupDatas = yii::$app->db->createCommand($getSql)->queryAll();
                if(!$groupDatas) {
                    break;
                }
                
                $groupLogId = [];
                foreach($groupDatas as $groupData) {
                    $groupLogId[] = $groupData['id'];
                    if(!$groupData['step'] || ! in_array($groupData['step'], $this->stepArr)) {
                        continue;
                    }
                    if(!$groupData['site_name'] || ! in_array($groupData['site_name'], $this->siteArr)) {
                        continue;
                    }
                    if(!$groupData['mail_type'] || ! in_array($groupData['mail_type'], $this->mailTypeArr)) {
                        continue;
                    }
                    
                    $siteId = $this->webIndex[$groupData['site_name']];  //站点ID
                    $siteType = $this->getSiteType($siteId);  //站点类型 0未定义, 1电子, 2服装
                    $groupData["site_id"] = $siteId;
                    $groupData["site_type"] = $siteType;

                    //取计划发送日期
                    $planParam = [
                            "site_id" => $siteId,
                            "mail_type" => $groupData["mail_type"],
                            "mail_type_arr" => $this->mailTypeArr,
                    ];
                    $planData = $pushGroupLogModel->getPlanSendDate($planParam);
                    $groupData["plan_send_date"] = isset($planData["data"]) ? $planData["data"] : "";

                    //入库
                    $result = $pushGroupLogModel->doSavePushGroupLog($groupData);
                    
                    
                }
                
                if($groupLogId) {
                    // 修改已经处理的数据状态
                    yii::$app->db->createCommand("update gb_push_group_log set is_sync=1 where id in(".join(',', $groupLogId).")")->execute();
                }
                
                
            }
        }
        
	/**
	 * 取站点类型
	 */
	protected function getSiteType($siteId = 0)
	{
		$siteType = 0;
		$webType = Yii::$app->params["sites"]["marketing_email"]["web_type"];
		foreach ($webType as $type => $val)
		{
			if (isset($val["sites"][$siteId]))
			{
				$siteType = $type;
				break;
			}
		}
		return $siteType;
	}
	
	/**
	 * 验证数据合法性
	 */
	protected function doVaildationData()
	{
		$post = $this->post;
		
		//基础数据判断
		if (empty($post['data']) || empty($post['token']))
		{
			$return = [
				"code" => $this->result[1]["code"],
				"msg" => $this->result[1]["msg"],
			];
			die(json_encode($return));
		}
		
		//把json数据转成数组
		$json = $post["data"];
		$data = json_decode(urldecode($json), true);
		$this->data = $data;  //赋值
		
		//token核对
		$inToken = $post["token"];
		$token = md5($this->getApiKey() . $json);
		if ($token != $inToken)
		{
			$return = [
				"code" => $this->result[2]["code"],
				"msg" => $this->result[2]["msg"],
			];
			die(json_encode($return));
		}
		
		//推送环节 验证
		$step = isset($data["step"]) ? intval($data["step"]) : 0;  //推送环节
		if (! $step || ! in_array($step, $this->stepArr))
		{
			$return = [
				"code" => $this->result[4]["code"],
				"msg" => $this->result[4]["msg"],
			];
			die(json_encode($return));
		}
		
		//站点名称验证
		$siteName = isset($data["site_name"]) ? trim($data["site_name"]) : "";  //	站点名称
		if (! $siteName || ! in_array($siteName, $this->siteArr))
		{
			$return = [
				"code" => $this->result[5]["code"],
				"msg" => $this->result[5]["msg"],
			];
			die(json_encode($return));
		}
		
		//邮件类型 验证
		$mailType = isset($data["mail_type"]) ? intval($data["mail_type"]) : 0;  //邮件类型，例如1:购物车、2:浏览记录
		if (! $mailType || ! in_array($mailType, $this->mailTypeArr))
		{
			$return = [
				"code" => $this->result[6]["code"],
				"msg" => $this->result[6]["msg"],
			];
			die(json_encode($return));
		}
	}
	
	/**
	 * 获取密钥
	 */
	protected function getApiKey()
	{
		//如果是正式环境,则根据step,site_name来取密钥
		if (YII_ENV_PROD)
		{
			$step = $this->data["step"];
			$siteName = $this->data['site_name'];
			if (isset($this->apiKeyList[$step][$siteName]))
			{
				$apiKey = $this->apiKeyList[$step][$siteName];
			}
			elseif (isset($this->apiKeyList[$step]["default"]))
			{
				$apiKey = $this->apiKeyList[$step]["default"];
			}
			else
			{
				$apiKey = self::DEFAULT_API_KEY;
			}
		}
		else
		{
			//测试环境统一密钥
			$apiKey = self::DEFAULT_API_KEY;
		}
		return $apiKey;
	}
	
	/**
	 * 保存原始数据作为日志(只有合法的数据的才会写入日志)
	 */
	protected function doWriteLog($response = [])
	{
		if ($this->post && $this->data)
		{
			//写数据库
			$insert = [
				"step" => $this->data["step"],
				"site_name" => $this->data["site_name"],
				"request_data" => json_encode($this->post),
				"response_data" => json_encode($response),
				"create_time" => Yii::$app->systime->time()
			];
			$pushGroupLogRequestsModel = new PushGroupLogRequests();
			$status = $pushGroupLogRequestsModel->saveData($insert);
		}
	}
}